package com.spa.common.cofing;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;

import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

/**
 * Swagger2 配置文件
 * 
 * @author P0081447
 *
 */
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {

	@Autowired
	private Environment environment;

	@Bean
	public Docket docket() {
		// 设置显示的swagger环境信息
		Profiles profiles = Profiles.of("dev", "test");
		// 判断是否处在自己设定的环境当中
		boolean flag = environment.acceptsProfiles(profiles);

		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).groupName("分组名称") // 配置api文档的分组
				.enable(flag) // 配置是否开启swagger
				.select().apis(RequestHandlerSelectors.basePackage("com.spa.modules")) // 配置扫描路径
				.paths(PathSelectors.any()) // 配置过滤哪些
				.build().globalOperationParameters(setHeaderToken());
	}
	
	 /**
     * 解决springboot2.6 和springfox不兼容问题
     * @return
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }

	/**
	 * token
	 * 
	 * @return
	 */
	private List<Parameter> setHeaderToken() {
		ParameterBuilder tokenPar = new ParameterBuilder();
		List<Parameter> pars = new ArrayList<>();
		tokenPar.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header")
				.required(false).build();
		pars.add(tokenPar.build());
		return pars;
	}

	// api基本信息
	private ApiInfo apiInfo() {
		return new ApiInfo("spa-cli-admin 接口API", "spa-cli-admin 接口API", "v1.0", "http://",
				new Contact("512878722@qq.com", "512878722@qq.com", "145xxxxx@qq.com"), // 作者信息
				"Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<>());
	}
}